﻿using Common.AspNetCore;
using Common.Infrastructure;
using Log.Api.Extensions;
using Log.Api.IService;
using Log.Api.LogModels;
using Log.Api.QueryModel;
using Log.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log.Api.Service
{
    public class SyncLogService : CommonService
    {
        ////private IBaseEsContextService esContextService;
        private IEsClientProviderService clientProvider;
        private string indexName = "minigroupsynclog";
        private readonly IOptions<EsConfig> config;
        private readonly bool isSaveByHttp;

        /// <summary>
        /// 索引名称
        /// </summary
        public SyncLogService(IServiceProvider provider, IEsClientProviderService client, IConfiguration c, IOptions<EsConfig> config) : base(provider)
        {
            this.clientProvider = client;
            this.config = config;
            this.isSaveByHttp = LibSysUtils.ToBoolean(c["IsAddByHttp"]);
        }

        public ElasticClient GetClient()
        {
            return this.clientProvider.GetClient(indexName);
        }

        /// <summary>
        /// 插入
        /// </summary>
        public async Task<bool> InsertAsync(SyncLogModel model)
        {
            if (this.isSaveByHttp)
            {
                await ElasticsearchUtils.SaveSyncLogAsync(this.config.Value.Urls[0], indexName, model);
                return true;
            }
            else
            {
                var client = GetClient();
                var response = await client.CreateDocumentAsync(model);
                return response.IsValid;
            }
        }

        /// <summary>
        /// 根据Id删除数据
        /// </summary>
        public bool DeleteById<T>(string id) where T : class
        {
            var client = GetClient();
            var response = client.Delete<T>(id);
            return response.IsValid;
        }

        /// <summary>
        /// 根据条件获取日志
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<SyncLogModel> GetSyncLoges(SyncLogQuery query)
        {
            var client = GetClient();
            var response = client.Search<SyncLogModel>(s => s.Query(q => (q.Match(w => w.Field(f => f.Msg).Query(query.Parameter))
           || q.Match(w => w.Field(f => f.Api).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncId).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncCode).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncName).Query(query.Parameter)))
             && q.Match(w => w.Field(f => f.ApiKey).Query(query.ApiKey))
             && +q.DateRange(d => d.Field(f => f.CT).GreaterThanOrEquals(query.BeginTime).LessThan(query.EndTime))).Sort(s => s.Descending(d => d.CT)).From((query.PageIndex - 1) * query.PageSize).Take(query.PageSize));
            return response.Documents.ToList();
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public long GetTotalCount(SyncLogQuery query)
        {
            var client = GetClient();
            var response = client.Search<SyncLogModel>(s => s.Query(q => (q.Match(w => w.Field(f => f.Msg).Query(query.Parameter))
           || q.Match(w => w.Field(f => f.Api).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncId).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncCode).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncName).Query(query.Parameter)))
             && q.Match(w => w.Field(f => f.ApiKey).Query(query.ApiKey))
             && +q.DateRange(d => d.Field(f => f.CT).GreaterThanOrEquals(query.BeginTime).LessThan(query.EndTime))));
            return response.Total;
        }

        /// <summary>
        /// 获取所有日志
        /// </summary>
        /// <returns></returns>
        public List<SyncLogModel> GetAllSyncLoges()
        {
            var client = GetClient();
            var searchDescriptor = new SearchDescriptor<SyncLogModel>();
            searchDescriptor = searchDescriptor.Query(p => p.MatchAll());
            var response = client.Search<SyncLogModel>(searchDescriptor);
            return response.Documents.ToList();
        }

        /// <summary>
        /// 删除指定日志数据
        /// </summary>
        /// <returns></returns>
        public bool DeleteByQuery(SyncLogQuery query)
        {
            var client = GetClient();
            var response = client.DeleteByQuery<SyncLogModel>(s => s.Query(q => (q.Match(w => w.Field(f => f.Msg).Query(query.Parameter))
           || q.Match(w => w.Field(f => f.Api).Query(query.Parameter))
            || q.Match(w => w.Field(f => f.SyncId).Query(query.Parameter)))
             && q.Match(w => w.Field(f => f.ApiKey).Query(query.ApiKey))
             && +q.DateRange(d => d.Field(f => f.CT).GreaterThanOrEquals(query.BeginTime).LessThan(query.EndTime))));
            return response.IsValid;
        }
    }
}
